package sv.edu.edutec.fotos.servlet;

import java.io.IOException;
import java.sql.Blob;
import java.util.Map;

import javax.swing.text.StyledEditorKit.BoldAction;
import javax.validation.Valid;

import org.apache.commons.io.IOUtils;
import org.hibernate.Hibernate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import sv.edu.edutec.fotos.model.TblPhoto;
import sv.edu.edutec.fotos.service.PhotoService;

@Component
@Controller
public class PhotoServlet {
	
	@Autowired
	PhotoService photoService;
	
	@RequestMapping({"/","showPhoto"})
	public String showColegio(Map<String, Object> map){
		//map.put("photo", new TblPhoto());
		map.put("photoList", photoService.listPhotos());
		return "/photo";
	}
	
	@RequestMapping({"/","showPhotos"})
	public String showPhoto(Map<String, Object> map){
		map.put("photo", new TblPhoto());
		
		return "/addPhoto";
	}
	
	@RequestMapping(value = "addPhoto", method = RequestMethod.POST)
	public String addPhotos(@ModelAttribute("photo")  TblPhoto tblPhoto,@RequestParam("file") MultipartFile file){
		System.out.println("ingresando Photo: ");
		System.out.println("Title: " + tblPhoto.getTitle());
		System.out.println("Content Type: " + file.getContentType());
		
			try{
				Authentication a = SecurityContextHolder.getContext().getAuthentication();
				User u = (User)a.getPrincipal();
				tblPhoto.setOwner(u.getUsername());				
				tblPhoto.setPhotoFile(IOUtils.toByteArray(file.getInputStream()));
				photoService.addPhoto(tblPhoto);
			}
			catch(DataAccessException ex){
				ex.printStackTrace();
			}
			catch(IOException ex){
				ex.printStackTrace();
			}
			
			
		
			
		
		return "redirect:/showPhoto";
	}

}
